package top.lshaci.learning.oauth2.gateway.config;

import cn.hutool.core.util.ArrayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.oauth2.server.resource.authentication.ReactiveJwtAuthenticationConverterAdapter;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import reactor.core.publisher.Mono;
import top.lshaci.learning.oauth2.gateway.properties.Oauth2GatewayProperties;

import static top.lshaci.learning.oauth2.gateway.util.WebUtil.writeToResponse;

/**
 * Oauth2GatewayConfig
 *
 * @author lshaci
 * @since 1.0.0
 */
@Configuration
@EnableWebFluxSecurity
@EnableConfigurationProperties(Oauth2GatewayProperties.class)
public class Oauth2GatewayConfig {

//    private AuthorizationManager authorizationManager;

    @Autowired
    private Oauth2GatewayProperties properties;

    @Bean
    public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
        http.oauth2ResourceServer().jwt()
                .jwtAuthenticationConverter(jwtAuthenticationConverter());

        http.oauth2ResourceServer().authenticationEntryPoint(authenticationEntryPoint());

        // 授权配置
        ServerHttpSecurity.AuthorizeExchangeSpec authorizeExchange = http.authorizeExchange();
        if (ArrayUtil.isEmpty(properties.getWhiteListUrl())) {
            authorizeExchange.pathMatchers(properties.getWhiteListUrl()).permitAll();
        }
        authorizeExchange
                // 允许所有options
                .pathMatchers(HttpMethod.OPTIONS).permitAll()
                .anyExchange().authenticated()
        ;

        // csrf配置
        http.csrf().disable();

        // 配置异常处理器
        http.exceptionHandling()
                // 身份验证的入口 (invalid_token  or  no_token)
                .authenticationEntryPoint(authenticationEntryPoint())
                // 无权限的处理器
                .accessDeniedHandler(accessDeniedHandler())
        ;

        return http.build();
    }

    /**
     * 未授权
     *
     * @return
     */
    @Bean
    ServerAccessDeniedHandler accessDeniedHandler() {
        return (exchange, denied) -> {
            Mono<Void> mono = Mono
                    .defer(() -> Mono.just(exchange.getResponse()))
                    .flatMap(response -> writeToResponse(exchange.getResponse(), 40003, "无权限"));

            return mono;
        };
    }

    /**
     * token无效或者已过期自定义响应
     */
    @Bean
    ServerAuthenticationEntryPoint authenticationEntryPoint() {
        return (exchange, e) -> {
            Mono<Void> mono = Mono.defer(() -> Mono.just(exchange.getResponse()))
                    .flatMap(response -> writeToResponse(exchange.getResponse(), 40001, "请登录"));
            return mono;
        };
    }

    /**
     * 自定义 jwt 认证转换器（还没有搞懂）
     * <pre>
     *     https://blog.csdn.net/qq_24230139/article/details/105091273
     *     ServerHttpSecurity没有将jwt中authorities的负载部分当做Authentication
     *     需要把jwt的Claim中的authorities加入
     *     方案：重新定义R 权限管理器，默认转换器JwtGrantedAuthoritiesConverter
     * </pre>
     * @return ReactiveJwtAuthenticationConverterAdapter
     */
    @Bean
    public ReactiveJwtAuthenticationConverterAdapter jwtAuthenticationConverter() {
        JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
        jwtGrantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");
        jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("authorities");

        JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
        jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);
        return new ReactiveJwtAuthenticationConverterAdapter(jwtAuthenticationConverter);
    }
}
